import router from "@/router"
import store from "@/store";
import axios from "axios"
import {baseURL, timeout, authKey , duration} from "@/config/constant"
import {Message} from "element-ui";
import NProgress from '../plugins/nprogress'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 配置全局
const request = axios.create({
    baseURL,
    timeout
})

/**
 * 请求拦截器
 */
request.interceptors.request.use(config => {
    console.log(config)
    // 获取 token
    NProgress.start();
    let token = store.state.user.userToken;
    // 携带请求头信息
    if (token && token.length > 0) {
        config.headers[authKey] = token;
    }
    return config;
})

/**
 * 响应拦截器
 */
request.interceptors.response.use(config => {
        console.log(config)
        let response = config.data;
        NProgress.done();
        if (response instanceof Blob) {
            return config;
        }
        if (response.code >= 50000) {
            // 后端 50001 ~ 50006 全是登录失败
            if (response.code >= 50001 && response.code <= 50006) {
                localStorage.removeItem(authKey);
                router.replace({path: "/login"})
            }
            Message.error({message: response.msg});
        }
        if (response.code >= 20000 && response.code < 30000) {
            if (response.msg && response.msg !== "") {
                Message.success({message: response.msg, duration});
            }
        }
        return response.data;
    },
    error => {
        NProgress.done();
        let {message} = error;
        if (message === 'Network Error') {
            message = '服务器接口连接异常'
        } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    })

export default request;